//
//  PhotoImageView.m
//  suRead
//
//  Created by lidi on 15/11/9.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "PhotoImageView.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"

@interface PhotoImageView()

@property (nonatomic,assign)CGSize sizeInit; //初始大小

@end

@implementation PhotoImageView

- (instancetype)initWithURL:(NSString *)url_ placeHolder:(UIImage *)placeHolder_
{
    if (self=[super init]) {
        self.contentMode = UIViewContentModeScaleAspectFit;
        
        __weak typeof(self) weak_self = self;
        CGSize screenSize = [UIScreen mainScreen].bounds.size;

        [self sd_setImageWithURL:[NSURL URLWithString:url_] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                weak_self.sizeInit = [weak_self displayedImageBounds].size;
                weak_self.currentScale = 1.0f;
                
                [weak_self mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.edges.equalTo(weak_self.superview).insets(UIEdgeInsetsZero);
                    
                    CGFloat height = weak_self.sizeInit.height;
                    if (height < screenSize.height) {
                        height = screenSize.height;
                    }
                    
                    make.size.mas_equalTo(CGSizeMake(weak_self.sizeInit.width, height));
                }];
                
                weak_self.userInteractionEnabled = YES;
                
                UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:weak_self action:@selector(photoDoubleClicked:)];
                doubleTap.numberOfTapsRequired = 2;
                [weak_self addGestureRecognizer:doubleTap];
                
                UIPinchGestureRecognizer *pinchGes = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(photoPinch:)];
                [weak_self addGestureRecognizer:pinchGes];
                
                UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:weak_self action:@selector(photoTap:)];
                oneTap.numberOfTapsRequired = 1;
                [oneTap requireGestureRecognizerToFail:doubleTap];
                [weak_self addGestureRecognizer:oneTap];
                
            });
            
        }];

    }
    
    return self;
}

- (void)photoTap:(UITapGestureRecognizer *)ges
{
    if (self.photoImageViewTap) {
        self.photoImageViewTap();
    }

}

- (void)photoDoubleClicked:(UITapGestureRecognizer *)ges
{
    if (self.currentScale < 2.0f) {
        self.currentScale = 2.0f;
    }
    else {
        self.currentScale = 1.0f;
    }
    
    CGFloat scale_ = self.currentScale;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    
    UIImageView *photoImageView = (UIImageView *)ges.view;
    [photoImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(photoImageView.superview).insets(UIEdgeInsetsZero);
        
        CGFloat height = self.sizeInit.height * scale_;
        if (height < screenSize.height) {
            height = screenSize.height;
        }
        
        make.size.mas_equalTo(CGSizeMake(self.sizeInit.width * scale_, height));
    }];
    
    [UIView animateWithDuration:.2f animations:^{
        [photoImageView.superview layoutIfNeeded];
    }];
    
}

- (void)photoPinch:(UIPinchGestureRecognizer *)ges
{
    CGFloat scale_ = ges.scale - 1.0f + self.currentScale;
    
    if (scale_ > 2.0f) {
        scale_ = 2.0f;
    }
    
    if (scale_ < .5f) {
        scale_ = .5f;
    }
    
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    
    UIImageView *photoImageView = (UIImageView *)ges.view;
    [photoImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(photoImageView.superview).insets(UIEdgeInsetsZero);
        
        CGFloat height = self.sizeInit.height * scale_;
        if (height < screenSize.height) {
            height = screenSize.height;
        }
        
        make.size.mas_equalTo(CGSizeMake(self.sizeInit.width * scale_, height));
    }];
    
    if (ges.state == UIGestureRecognizerStateEnded) {
        
        self.currentScale = scale_;
        
        if (scale_ < 1.0f) {
            scale_ = 1.0f;
            [self resetScale];
        }
        
    }
    
}

- (void)resetScale
{
    __weak typeof(self) weak_self = self;
    self.currentScale = 1.0f;
    CGFloat scale_ = self.currentScale;

    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.superview).insets(UIEdgeInsetsZero);
        
        CGFloat height = weak_self.sizeInit.height * scale_;
        if (height < screenSize.height) {
            height = screenSize.height;
        }
        
        make.size.mas_equalTo(CGSizeMake(weak_self.sizeInit.width * scale_, height));
    }];
    
    [UIView animateWithDuration:.2f animations:^{
        [weak_self.superview layoutIfNeeded];
    }];
}

- (CGRect)displayedImageBounds
{
    UIImage *image = [self image];
    if(self.contentMode != UIViewContentModeScaleAspectFit || !image)
        return CGRectInfinite;
    
    CGFloat boundsWidth  = [self bounds].size.width,
    boundsHeight = [self bounds].size.height;
    
    CGSize  imageSize  = [image size];
    CGFloat imageRatio = imageSize.width / imageSize.height;
    CGFloat viewRatio  = boundsWidth / boundsHeight;
    
    if(imageRatio < viewRatio) {
        CGFloat scale = boundsHeight / imageSize.height;
        CGFloat width = scale * imageSize.width;
        CGFloat topLeftX = (boundsWidth - width) * 0.5;
        return CGRectMake(topLeftX, 0, width, boundsHeight);
    }
    
    CGFloat scale = boundsWidth / imageSize.width;
    CGFloat height = scale * imageSize.height;
    CGFloat topLeftY = (boundsHeight - height) * 0.5;
    
    return CGRectMake(0, topLeftY, boundsWidth, height);
}

@end
